package cn.whb.hrm.smslogin;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsLoginFilter extends OncePerRequestFilter{
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        //获取当前请求的uri
        String uri = httpServletRequest.getRequestURI();
        //判断uri是否是验证码登录
        if("/smslogin".equals(uri)){
            String phone = httpServletRequest.getParameter("phone");
            String code = httpServletRequest.getParameter("code");
            //获取当前请求的会话，从会话中的到验证码
            String scode = (String)httpServletRequest.getSession().getAttribute("smsCode::" + phone.toString());
            //如果用户没有传参数或者用户的参数与session中的验证码不一致，抛出一个错误
            if(code != null && !code.equalsIgnoreCase(scode)){
                throw new RuntimeException("验证码错误");
            }
        }
        //其他的请求放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
